﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Principal;
using System.IO;

namespace KALE_Scanning {
    public class BrowseDoc : IDisposable {
       private string sAdres;
       private string libraryName;
       private System.Windows.Forms.OpenFileDialog ofd;
       private System.Windows.Forms.SaveFileDialog sfd;
       public BrowseDoc(ref System.Windows.Forms.OpenFileDialog _ofd,string libraryName,string sAdres)
       {
           this.sAdres = sAdres;
           this.libraryName = libraryName;
           ofd = _ofd;
           setSettingValues();
           
       }
       public BrowseDoc(ref System.Windows.Forms.SaveFileDialog _sfd, string libraryName, string sAdres)
       {
           this.sAdres = sAdres;
           this.libraryName = libraryName;
           sfd = _sfd;
           setSettingValues();

       }
       private string settingOpenPath = "";
       private string settingSavePath = "";
       private void setSettingValues()
       {
           settingOpenPath = KALE_Scanning.Properties.Settings.Default.OpenfileDialog.Replace("%UserName%", WindowsIdentity.GetCurrent().Name);
           settingSavePath = KALE_Scanning.Properties.Settings.Default.SaveFileFolder;
       }
       public string OpenPath {
           get {return settingOpenPath;}
           set {
               settingOpenPath = value;
           }
       }
       public string SavePath {
           get{return settingSavePath;}
           set {
               settingSavePath = value;
           }
       }

       public bool SaveFileDialog(string fileFilter, byte[] fileByte)
       {
           try
           {
               saveenbas:
            sfd.Title = "Dosya ismi giriniz";
            sfd.Filter = fileFilter;
            sfd.FilterIndex = 0;
            sfd.InitialDirectory = this.settingSavePath;
            
            if(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
               
                if(sfd.CheckFileExists)
                {
                    AGC_WebServices.Service service = new AGC_WebServices.Service();
                    //service.UseDefaultCredentials = true;
                    service.Credentials = UserProperty.UserProperties.Credential;
                    if (service.CheckFileName(sAdres, libraryName, sfd.FileName) == false) {
                        System.Windows.Forms.MessageBox.Show("Arşiv kütüphanesinde aynı isimli bir dosya mevcuttur.");
                        goto saveenbas;
                    }

                    this.SavePath = sfd.FileName;
                    FileInfo inf = new FileInfo(sfd.FileName);
                    this.SavePath = Utility.CheckPathSlash(this.SavePath) + inf.Name;
                savebaslangic:
                    if(File.Exists(this.SavePath))
                    {
                        if(System.Windows.Forms.MessageBox.Show("Aynı isimde bir dosya var. İsim değiştirilsin mi ?", "Dosya İsmi", System.Windows.Forms.MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                        {
                            
                            ChangeFileName cfn = new ChangeFileName(inf.Name.Replace(inf.Extension,""));
                            if(cfn.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                Utility.NewFileNameContainer = Utility.NewFileNameContainer + inf.Extension;
                                this.SavePath = this.SavePath.Replace(inf.Name, Utility.NewFileNameContainer);
                                
                                goto savebaslangic;
                            } else {
                                //sorduralım en azından
                                File.Delete(this.SavePath);
                                goto saveenbas;
                            }
                            

                        }

                        else
                        {
                            return false;
                        }
                        
                    }

                    FileStream fs = File.OpenWrite(sfd.FileName);
                    fs.Write(fileByte, 0, fileByte.Length);
                    fs.Close();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
        public string SavePath
        {
            get { return settingSavePath; }
            set
            {
                return false;
            }
           }
           catch (Exception ex)
           {
               System.Windows.Forms.MessageBox.Show("Dosya kaydedilirken bir hata oluştu.\nError :\n" + ex.Message +"\nStackTrace :\n"+ ex.StackTrace, "Hata", System.Windows.Forms.MessageBoxButtons.OK, System.Windows.Forms.MessageBoxIcon.Error);
               return false;
           }
       }
        public byte[] OpenDialog()
        {
        enbas:
            ofd.Title = "Lütfen Dosya Seçiniz";
            ofd.Filter = " (*.doc)|*.doc|(*.docx)|*.docx|(*.xls)|*.xls|(*.xlsx)|*.xlsx|(*.ppt)|*.ppt|(*.pptx)|*.pptx" +
                "|(*.pdf)|*.pdf|(*.txt)|*.txt|(*.rtf)|*.rtf";
            ofd.FilterIndex = 7;
            ofd.InitialDirectory = this.OpenPath;
            
            if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (ofd.CheckFileExists)
                {
                    AGC_WebServices.Service service = new AGC_WebServices.Service();
                    //service.UseDefaultCredentials = true;
                    service.Credentials = UserProperty.UserProperties.Credential;
                    
                    if (service.CheckFileName(sAdres, libraryName, ofd.SafeFileName) == false)
                    {
                        System.Windows.Forms.MessageBox.Show("Arşiv kütüphanesinde aynı isimli bir dosya mevcuttur.");
                        goto enbas;
                    }

                    this.OpenPath = ofd.FileName;
                    FileInfo inf = new FileInfo(ofd.FileName);
                
                    this.SavePath = Utility.CheckPathSlash(this.SavePath) + inf.Name;
                    string name = inf.Name;
                baslangic:
                    
                    if (File.Exists(this.SavePath))
                    {
                        
                        if (System.Windows.Forms.MessageBox.Show("Aynı isimde bir dosya var. İsim değiştirilsin mi ?", "Dosya İsmi", System.Windows.Forms.MessageBoxButtons.OKCancel) == System.Windows.Forms.DialogResult.OK)
                        {
                            
                            ChangeFileName cfn = new ChangeFileName(inf.Name.Replace(inf.Extension,""));
                            if (cfn.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                            {
                                Utility.NewFileNameContainer = Utility.NewFileNameContainer + inf.Extension;
                                this.SavePath = this.SavePath.Replace(name, Utility.NewFileNameContainer);
                                name = Utility.NewFileNameContainer;
                                goto baslangic;
                            }
                            //sorduralım en azından
                            File.Delete(this.SavePath);
                            goto enbas;
                        }

                        return null;
                    }

                    File.Copy(ofd.FileName, this.SavePath);
                    FileStream strm = new FileStream(ofd.FileName, FileMode.Open, FileAccess.Read);
                    byte[] fileContents = new Byte[strm.Length];
                    strm.Read(fileContents, 0, Convert.ToInt32(strm.Length));
                    strm.Close();
                    return fileContents;
                }
                return null;
            }
            return null;
            //string webUrl = cmbSunucu.SelectedItem.ToString();
            //SPCopy_WS.Copy copyService = new SPCopy_WS.Copy();
            //copyService.Url = webUrl + "_vti_bin/copy.asmx";

            //copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;
            //TODO
            //string sourceUrl = Application.StartupPath + "\\";
            // uint copyresult = copyService.CopyIntoItems(sourceUrl, destinationUrl, myFields, fileContents, out cResultArray);
        }
        public static bool DeleteFile(string filepath)
        {
            try
            {
                System.IO.File.Delete(filepath);
                return true;
            }
            catch
            {
                return false;
            }
        }

        public void Dispose()
        {
            GC.SuppressFinalize(this);
        }
    }
}
